import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import Configuration from './common/config/configuration';
import { EmployeeModule } from './employee/employee.module';
import { CustomerModule } from './customer/customer.module';
import { RegionModule } from './region/region.module';

@Module({
  imports: [
    /**
     * 环境变量
     * @params isGlobal 是否全局使用
     * @params ignoreEnvFile 是否忽略环境变量文件
     * @params envFilePath 环境变量路径
     * @params load 要加载的自定义配置文件数组
     */
    ConfigModule.forRoot({
      isGlobal: true,
      ignoreEnvFile: true,
      envFilePath: [],
      load: [Configuration],
    }),
    // 全局注册typeorm并配置连接参数
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (
        configService: ConfigService,
      ): Promise<TypeOrmModuleOptions> => {
        const tempHost: string = await configService.get('MYSQL_HOST');
        const tempPort: number = await configService.get('MYSQL_PORT');
        const tempUser: string = await configService.get('MYSQL_USER');
        const tempPassword: string = await configService.get('MYSQL_PASSWORD');
        const tempName: string = await configService.get('MYSQL_NAME');
        return {
          type: 'mysql',
          host: tempHost,
          port: tempPort,
          username: tempUser,
          password: tempPassword,
          database: tempName,
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: true,
        };
      },
    }),
    // 地区代码
    RegionModule,
    // 员工
    EmployeeModule,
    // 客户
    CustomerModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
